package com.lottery.im;

import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.lottery.im.api.result.entity.UserInfo;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.util.Foreground;
import com.lottery.im.util.GlideImageLoader;
import com.lottery.im.util.LogUtils;
import com.lottery.im.util.ResolutionUtil;
import com.lottery.im.util.SPUtils;
import com.lzy.imagepicker.ImagePicker;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.imsdk.TIMGroupReceiveMessageOpt;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushListener;
import com.tencent.imsdk.TIMOfflinePushNotification;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.qalsdk.sdk.MsfSdkUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

/**
 * Created by ztz on 2017/8/30.
 */

public class MyApplication extends MultiDexApplication {

  private static MyApplication mInstance;
  public static int count = 0;

  private String mToken;
  private UserInfo mUserInfo;

  @Override
  public void onCreate() {
    super.onCreate();
    Foreground.init(this);
    mInstance = this;
    LogUtils.isDebug = true;
    MultiDex.install(this);
    initTIM();
    initImagePicker();
    ZXingLibrary.initDisplayOpinion(this);
    ResolutionUtil.getInstance().init(this);
  }

  /*
   *  初始化一些腾讯云通信操作
   * */
  private void initTIM() {
    //离线推送  这里的离线指的是应用在没有退出登录的情况下，被系统或者用户杀掉。在这种情况下，如果还想收到 ImSDK 的消息提醒，可以集成云通信离线推送
    if (MsfSdkUtils.isMainProcess(this)) {
      TIMManager.getInstance().setOfflinePushListener(new TIMOfflinePushListener() {
        @Override
        public void handleNotification(TIMOfflinePushNotification notification) {
          if (notification.getGroupReceiveMsgOpt() == TIMGroupReceiveMessageOpt.ReceiveAndNotify) {
            //消息被设置为需要提醒
            notification.doNotify(getApplicationContext(), R.mipmap.ic_launcher);
          }
        }
      });
    }
    //清楚所有通知栏通知
    NotificationManager notificationManager = (NotificationManager) this
        .getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
    // TIM 奔溃日志、普通日志配置
    TIMSdkConfig config = new TIMSdkConfig(Constants.TIM_SDK_APPID)
        .enableCrashReport(false)
        .enableLogPrint(true)
        .setLogLevel(TIMLogLevel.DEBUG);
    //初始化imsdk
    TIMManager.getInstance().init(getApplicationContext(), config);
  }

  public static MyApplication getInstance() {
    return mInstance;
  }

  public void setToken(String token) {
    mToken = token;
  }

  public String getToken() {
    if (TextUtils.isEmpty(mToken)) {
      mToken = (String) SPUtils.get(this, SpKeyConstant.TOKEN_KEY, "");
    }
    return mToken;
  }

  public void setUserInfo(UserInfo userInfo) {
    mUserInfo = userInfo;
  }

  public UserInfo getUserInfo() {
    if (null == mUserInfo) {
      String userInfo = (String) SPUtils.get(this, SpKeyConstant.USERINFO_KEY, "");
      mUserInfo = new Gson().fromJson(userInfo, UserInfo.class);
    }
    // 防止极端情况 空指针
    if (null == mUserInfo) {
      mUserInfo = new UserInfo();
    }

    return mUserInfo;
  }

  /*
   *  全局设置下拉刷新+上拉加载更多的UI
   *  static 代码段可以防止内存泄露
   * */
  static {
    //设置全局的Header构建器
    SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
      @Override
      public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
        layout.setPrimaryColorsId(R.color.windowBackground);//全局设置主题颜色
        return new ClassicsHeader(context).setSpinnerStyle(
            SpinnerStyle.Translate).setAccentColor(Color.BLACK);//指定为经典Header，默认是 贝塞尔雷达Header
      }
    });
    //设置全局的Footer构建器
    SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
      @Override
      public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
        layout.setPrimaryColorsId(R.color.windowBackground);//全局设置主题颜色
        //指定为经典Footer，默认是 BallPulseFooter
        return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
      }
    });
  }

  /*
   *  初始化头像选择相关配置
   * */
  private void initImagePicker() {
    ImagePicker imagePicker = ImagePicker.getInstance();
    imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
    //imagePicker.setShowCamera(true);  //显示拍照按钮
    //imagePicker.setCrop(true);        //允许裁剪（单选才有效）
    //imagePicker.setSaveRectangle(true); //是否按矩形区域保存
    //imagePicker.setSelectLimit(9);    //选中数量限制
    //imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
    //imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
    //imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
    //imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
    //imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
  }

  public String getThirdAccId() {
    UserInfo userInfo = getUserInfo();
    if (null == userInfo) return "";
    return userInfo.getThirdAccId();
  }
}
